package org.domain.sigepac.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * Classe para validar CPF
 * 
 * @author paulo.correa
 */
public class CPFValidator implements Validator {
  
  public void validate(FacesContext contexto, UIComponent arg1, Object valor)
      throws ValidatorException {
    boolean cpfValido = validaCPF((String) valor);
    
    if (!cpfValido) {
      throw new ValidatorException(new FacesMessage(
          FacesMessage.SEVERITY_ERROR, "CPF Inv\u00e1lido!", "CPF Inv\u00e1lido!"));
    }
  }
  
  private static String calcDigVerif(String num) {
    
    int primDig, segDig;
    int soma = 0, peso = 10;
    for (int i = 0 ; i < num.length() ; i++) {
      soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;
    }
    
    if (soma % 11 == 0 || soma % 11 == 1) {
      primDig = 0;
    } else {
      primDig = 11 - (soma % 11);
    }
    
    soma = 0;
    peso = 11;
    for (int i = 0 ; i < num.length() ; i++) {
      soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;
    }
    soma += primDig * 2;

    if (soma % 11 == 0 || soma % 11 == 1) {
      segDig = 0;
    } else {
      segDig = 11 - (soma % 11);
    }
    
    return String.valueOf(primDig) + String.valueOf(segDig);
  }
  
  public static boolean validaCPF(String cpf) {
    if (cpf.length() != 11) {
      return false;
    }
    String numDig = cpf.substring(0, 9);
    return calcDigVerif(numDig).equals(cpf.substring(9, 11));
  }
}
